import Vue from 'vue'
import VueRouter from 'vue-router'
// 导入需要的组件
import Reg from '@/views/Reg/Reg.vue'
import Login from '@/views/Login/Login.vue'
import Main from '@/views/Main/Main.vue'
import store from '@/store/index.js'
import Home from '@/views/Menus/Home/Home.vue'
import UserInfo from '@/views/Menus/User/Userinfo.vue'
import UserAvatar from '@/views/Menus/User/UserAvatar.vue'
import UserPwd from '@/views/Menus/User/UserPwd.vue'
import ArtCate from '@/views/Menus/Article/ArtCate.vue'
import Artlist from '@/views/Menus/Article/Artlist.vue'
Vue.use(VueRouter)
// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
// 覆盖掉vue-router原生的push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
const routes = [
  {
    path: '/',
    redirect: '/home',
    component: Main,
    children: [
      { path: 'home', component: Home },
      { path: 'user-info', component: UserInfo },
      { path: 'user-avatar', component: UserAvatar },
      { path: 'user-pwd', component: UserPwd },
      { path: 'art-cate', component: ArtCate },
      { path: 'art-list', component: Artlist }
    ]
  },
  { path: '/reg', component: Reg },
  { path: '/login', component: Login }
]

const router = new VueRouter({
  routes
})
router.beforeEach((to, from, next) => {
  // 登录和注册页面，不需要访问权限，直接放行
  // 除此之外，其他路由地址，需要访问权限
  // 从vuex中获取token的值,并判断是否有token
  // 如果有token认为用户已经登录了,直接放行
  // 如果没有token认为用户没有登录则强制跳转到登录页面
  if (to.path === '/login' || to.path === '/reg') {
    next()
  } else {
    if (store.state.token) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
